﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Content;
using TimeTickService.Configs;
using TimeTickService.Models;

namespace TimeTickService
{
    public interface IMqHelper
    {
        void EnqueueAction(AddMQScheduleModel model);
    }

    public class MqHelper : IMqHelper
    {
        private readonly IConnectionFactory _connectionFactory;
        private readonly IRedisHelper _redisHelper;
        private readonly RabbitMqSetting _settings;

        public MqHelper(IConnectionFactory connectionFactory, IRedisHelper redisHelper, IOptions<RabbitMqSetting> settings)
        {
            _connectionFactory = connectionFactory;
            _redisHelper = redisHelper;
            _settings = settings.Value;
        }

        public void EnqueueAction(AddMQScheduleModel model)
        {
            using (var connection = _connectionFactory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: model.Topic, autoDelete: false);

                    IMapMessageBuilder b = new MapMessageBuilder(channel);

                    var basic = channel.CreateBasicProperties();
                    //channel.BasicPublish(model.Exchange, model.Topic, (IBasicProperties)b.GetContentHeader(), b.GetContentBody());

                    var queue_name = $"{_settings.QueuePrefix}{model.Topic}";

                    channel.BasicPublish(model.Exchange, queue_name, basic, Encoding.UTF8.GetBytes(model.Payload));

                    _redisHelper.KeyDelete(model.Key);
                }
            }
        }
    }

    public static class MqHelperExtensions
    {
        public static IServiceCollection AddMqHelper(this IServiceCollection services)
        {
            return services.AddSingleton<IMqHelper>(
                s => new MqHelper(s.GetService<IConnectionFactory>(), s.GetService<IRedisHelper>(),
                    s.GetService<IOptions<RabbitMqSetting>>()));
        }
    }
}
